option explicit

Const vbext_ct_ClassModule = 2
Const vbext_ct_Document = 100
Const vbext_ct_MSForm = 3
Const vbext_ct_StdModule = 1

Main

Sub Main
	Dim xl
	Dim fs
	Dim WBook
	Dim VBComp
	Dim Sfx
	Dim ExportFolder
	Dim subFolder
	
	'===================================================
	'			Exit if no parameters received
	'===================================================
	If Wscript.Arguments.Count <> 1 Then
		MsgBox "As the only argument, give the FULL path to an XLS file to extract all the VBA from it."
	
	
	Else
		Set xl = CreateObject("Excel.Application")
		Set fs = CreateObject("Scripting.FileSystemObject")
		xl.Visible = true
		Set WBook = xl.Workbooks.Open(Trim(wScript.Arguments(0)))
		
		'===================================================
		'		Name of root folder for source files
		'===================================================
		ExportFolder = WBook.Path & "\" & fs.GetBaseName(WBook.Name) & " Code"

		'===================================================
		'			Create source code folders
		'===================================================
		fs.CreateFolder(ExportFolder)
		
		
		
		'===================================================
		'			Loop through the VB Components
		'===================================================
		For Each VBComp In WBook.VBProject.VBComponents
			Select Case VBComp.Type
				
				'____________
				'		CLASS
				'
				Case vbext_ct_ClassModule, vbext_ct_Document
					Sfx = ".cls"					
					If fs.FileExists(ExportFolder & "\" & subFolder) then
						subFolder = "Classes"
					Else
						subFolder = "Classes"
						fs.CreateFolder(ExportFolder & "\" & subFolder)
					End If
				
				'___________
				'		FORM
				'
				Case vbext_ct_MSForm
					Sfx = ".frm"
					
					If fs.FileExists(ExportFolder & "\" & subFolder) then
						subFolder = "Forms"
					Else
						subFolder = "Forms"
						fs.CreateFolder(ExportFolder & "\" & subFolder)
					End If
					
				'_____________
				'		MODULE
				'
				Case vbext_ct_StdModule
					Sfx = ".bas"
					
					If  fs.FileExists(ExportFolder & "\" & subFolder) then
						subFolder = "Modules"
					Else
						subFolder = "Modules"
						fs.CreateFolder(ExportFolder & "\" & subFolder)
					End If
				
				'____________
				'		OTHER
				'
				Case Else
					Sfx = ""
			End Select			
			
		
		
			If Sfx <> "" Then
				On Error Resume Next
				Err.Clear
				
				'_______________________________
				'		EXPORT TO CORRECT FOLDER
				VBComp.Export ExportFolder & "\" & subFolder & "\" & VBComp.Name & Sfx
				If Err.Number <> 0 Then
					MsgBox "Failed to export " & ExportFolder & subFolder & "\" & "\" & VBComp.Name & Sfx
				End If
				On Error Goto 0
			End If
		Next

		xl.Quit
	End If
End Sub
